<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <title>登录页面</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入jQuery库，方便进行AJAX操作 -->
  <style>
    body {
      background-color: #f8f9fa;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
    <div class="row justify-content-center">
      <div class="col-md-6">
        <div class="card">
          <div class="card-header text-center">
            <h2>欢迎登录</h2>
          </div>
          <div class="card-body">
            <!-- 给登录表单添加id，方便后续通过JavaScript操作 -->
            <form id="loginForm" method="POST" action="#"> <!-- 修改action属性，避免默认提交行为导致页面刷新 -->
              <div class="mb-3">
                <label for="username" class="form-label">用户名：</label>
                <input type="text" id="username" name="username" class="form-control" required>
              </div>
              <div class="mb-3">
                <label for="password" class="form-label">密码：</label>
                <input type="password" id="password" name="password" class="form-control" required>
              </div>
              <div class="text-center">
                <input type="submit" value="登录" class="btn btn-primary">
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script>
    $(document).ready(function () {
      // 阻止登录表单的默认提交行为
      $('#loginForm').submit(function (e) {
        e.preventDefault();

        // 获取表单中的用户名和密码输入值
        var username = $('#username').val();
        var password = $('#password').val();

        // 使用AJAX发送POST请求到登录路由
        $.ajax({
          type: "POST",
          url: "/login",
          data: {
            username: username,
            password: password
          },
          dataType: "json",
          success: function (response) {
            if (response.success) {
              if (response.is_admin) {
                window.location.href = "{{ url_for('admin_panel') }}"; // 如果是管理员，重定向到管理员面板
              } else {
                window.location.href = "{{ url_for('user_panel') }}"; // 如果是普通用户，重定向到用户面板
              }
            } else {
              alert(response.message); // 如果登录失败，弹出相应提示框
            }
          },
          error: function () {
            alert("登录出现错误，请稍后再试"); // 如果请求出错，弹出错误提示
          }
        });
      });
    });
  </script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>